package com.community.common.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author esn
 */
public class ImgUtil {


    /**
     * @Desc: 从网络下载图片
     */
    public static void downloadByUrl(String imgUrl, String dirPath, String filenName) throws Exception {
        URL url = new URL(imgUrl);
        URLConnection con = url.openConnection();
        con.setConnectTimeout(5 * 1000);
        InputStream is = con.getInputStream();

        byte[] bs = new byte[1024];
        int len;
        File sf = new File(dirPath);
        if (!sf.exists()) {
            sf.mkdirs();
        }
        OutputStream os = new FileOutputStream(sf.getPath() + File.separator + filenName);
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        if (null != os) {
            os.close();
        }
        if (null != is) {
            is.close();
        }
    }


    /**
     * 网络图片转base64
     *
     * @param imageUrl
     * @return
     * @throws Exception
     */
    public static String imgToBase64(URL imageUrl) throws Exception {
        ByteArrayOutputStream outputStream = null;
        BufferedImage bufferedImage = ImageIO.read(imageUrl);
        outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outputStream.toByteArray());
    }

    /**
     * 图片转base64
     *
     * @param imageFile
     * @return
     * @throws Exception
     */
    public static String imgToBase64(File imageFile) throws Exception {
        ByteArrayOutputStream outputStream = null;
        StringBuffer buffer = new StringBuffer();
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        buffer.append(encoder.encode(outputStream.toByteArray()));
        return buffer.toString();
    }

    /**
     * base64串转图片
     *
     * @param base64
     * @param path
     * @param imgName
     * @throws Exception
     */
    public static void base64ToImg(String base64, String path, String imgName) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        FileOutputStream write = new FileOutputStream(new File(path + File.separator + imgName));
        byte[] decoderBytes = decoder.decodeBuffer(base64);
        write.write(decoderBytes);
        write.close();
    }


}